package service

import (
	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/model"

	"gorm.io/gorm"
)

// DictService 字典服务
type DictService struct {
	DB *gorm.DB
}

// NewDictService 创建字典服务实例
func NewDictService(db *gorm.DB) *DictService {
	return &DictService{DB: db}
}

// ============ 字典类型服务 ============

// GetDictTypeList 获取字典类型列表
func (s *DictService) GetDictTypeList(req dto.DictTypeListRequest) ([]*model.DictType, int64, error) {
	var dictTypes []*model.DictType
	var total int64

	query := s.DB.Model(&model.DictType{})

	// 条件查询
	if req.DictCode != "" {
		query = query.Where("dict_code LIKE ?", "%"+req.DictCode+"%")
	}
	if req.DictName != "" {
		query = query.Where("dict_name LIKE ?", "%"+req.DictName+"%")
	}
	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Order("id ASC").Offset(offset).Limit(req.PageSize).Find(&dictTypes).Error; err != nil {
		return nil, 0, err
	}

	return dictTypes, total, nil
}

// GetDictTypeByID 根据ID获取字典类型
func (s *DictService) GetDictTypeByID(id uint) (*model.DictType, error) {
	var dictType model.DictType
	if err := s.DB.First(&dictType, id).Error; err != nil {
		return nil, err
	}
	return &dictType, nil
}

// GetDictTypeByCode 根据编码获取字典类型
func (s *DictService) GetDictTypeByCode(code string) (*model.DictType, error) {
	var dictType model.DictType
	if err := s.DB.Where("dict_code = ?", code).First(&dictType).Error; err != nil {
		return nil, err
	}
	return &dictType, nil
}

// CreateDictType 创建字典类型
func (s *DictService) CreateDictType(req dto.CreateDictTypeRequest) (*model.DictType, error) {
	dictType := model.DictType{
		DictCode: req.DictCode,
		DictName: req.DictName,
		Status:   req.Status,
		Remark:   req.Remark,
	}

	if err := s.DB.Create(&dictType).Error; err != nil {
		return nil, err
	}
	return &dictType, nil
}

// UpdateDictType 更新字典类型
func (s *DictService) UpdateDictType(id uint, req dto.UpdateDictTypeRequest) (*model.DictType, error) {
	dictType, err := s.GetDictTypeByID(id)
	if err != nil {
		return nil, err
	}

	dictType.DictCode = req.DictCode
	dictType.DictName = req.DictName
	dictType.Status = req.Status
	dictType.Remark = req.Remark

	if err := s.DB.Save(dictType).Error; err != nil {
		return nil, err
	}
	return dictType, nil
}

// DeleteDictType 删除字典类型
func (s *DictService) DeleteDictType(id uint) error {
	// 检查是否有关联的字典数据
	var count int64
	if err := s.DB.Model(&model.DictData{}).Where("dict_type_id = ?", id).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return gorm.ErrRecordNotFound // 可以自定义错误
	}

	return s.DB.Delete(&model.DictType{}, id).Error
}

// ============ 字典数据服务 ============

// GetDictDataList 获取字典数据列表
func (s *DictService) GetDictDataList(req dto.DictDataListRequest) ([]*model.DictData, int64, error) {
	var dictDataList []*model.DictData
	var total int64

	query := s.DB.Model(&model.DictData{})

	// 条件查询
	if req.DictCode != "" {
		query = query.Where("dict_code = ?", req.DictCode)
	}
	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Order("dict_sort ASC, id ASC").Offset(offset).Limit(req.PageSize).Find(&dictDataList).Error; err != nil {
		return nil, 0, err
	}

	return dictDataList, total, nil
}

// GetDictDataByCode 根据字典编码获取字典数据（不分页，用于前端下拉框）
func (s *DictService) GetDictDataByCode(dictCode string) ([]*model.DictData, error) {
	var dictDataList []*model.DictData

	if err := s.DB.Where("dict_code = ? AND status = 1", dictCode).
		Order("dict_sort ASC, id ASC").
		Find(&dictDataList).Error; err != nil {
		return nil, err
	}

	return dictDataList, nil
}

// GetDictDataByID 根据ID获取字典数据
func (s *DictService) GetDictDataByID(id uint) (*model.DictData, error) {
	var dictData model.DictData
	if err := s.DB.First(&dictData, id).Error; err != nil {
		return nil, err
	}
	return &dictData, nil
}

// CreateDictData 创建字典数据
func (s *DictService) CreateDictData(req dto.CreateDictDataRequest) (*model.DictData, error) {
	dictData := model.DictData{
		DictTypeID: req.DictTypeID,
		DictCode:   req.DictCode,
		DictLabel:  req.DictLabel,
		DictValue:  req.DictValue,
		DictSort:   req.DictSort,
		CssClass:   req.CssClass,
		ListClass:  req.ListClass,
		IsDefault:  req.IsDefault,
		Status:     req.Status,
		Remark:     req.Remark,
	}

	if err := s.DB.Create(&dictData).Error; err != nil {
		return nil, err
	}
	return &dictData, nil
}

// UpdateDictData 更新字典数据
func (s *DictService) UpdateDictData(id uint, req dto.UpdateDictDataRequest) (*model.DictData, error) {
	dictData, err := s.GetDictDataByID(id)
	if err != nil {
		return nil, err
	}

	dictData.DictTypeID = req.DictTypeID
	dictData.DictCode = req.DictCode
	dictData.DictLabel = req.DictLabel
	dictData.DictValue = req.DictValue
	dictData.DictSort = req.DictSort
	dictData.CssClass = req.CssClass
	dictData.ListClass = req.ListClass
	dictData.IsDefault = req.IsDefault
	dictData.Status = req.Status
	dictData.Remark = req.Remark

	if err := s.DB.Save(dictData).Error; err != nil {
		return nil, err
	}
	return dictData, nil
}

// DeleteDictData 删除字典数据
func (s *DictService) DeleteDictData(id uint) error {
	return s.DB.Delete(&model.DictData{}, id).Error
}
